package otherdex;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Created by Administrator on 2017/4/1.
 * 中文转换成拼音
 */

public class PingyinUtil {

    /**
     * 将字符串中的中文转化为拼音,英文字符不变
     *
     * @param string 汉字
     * @return
     */
    public static String getPingYin(@NonNull String string) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        StringBuilder output = new StringBuilder();
        if (!TextUtils.isEmpty(string)) {
            char[] input = string.trim().toCharArray();
            try {
                for (char anInput : input) {
                    if (Character.toString(anInput).matches("[\\u4E00-\\u9FA5]+")) {
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(anInput, format);
                        if (temp != null && temp.length > 0)
                            output.append(temp[0]);
                    } else
                        output.append(Character.toString(anInput));
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        } else {
            return "";
        }
        return output.toString();
    }


    public static int aa(int a, int b) {
        return a / b;
    }

}

